import sys
sys.path.insert(0, "/home/lighthouse/my-dream")
import requests
from bs4 import BeautifulSoup
from middle_script import save_file
from module import config



class Weather():
    def __init__(self):
        self.headers = {
            "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
            "sec-ch-ua": '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"',
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
        }
    # 获取天气信息
    def get_weather(self,city_id):
        url = config.get_config(["weather", "weather_url"]).format(cityid=city_id)
        res = requests.get(url=url, headers=self.headers,verify=False)
        return res.json()
    # 爬虫获取城市编码
    def get_city_code(self):
        url = config.get_config(["weather", "code_url"])
        res = requests.get(url=url, headers=self.headers)
        bs = BeautifulSoup(res.content.decode('utf-8'), 'html.parser')
        # province为省份
        province = bs.find_all('h3')
        # contents为具体信息
        contents = bs.find_all('code', class_="nohighlight hljs")
        for i in range(1, len(province)):
            print(province[i].text)
            print(contents[i].text)
            final_text = province[i].text + "\n" + contents[i].text
            save_file().save_txt(filename=config.get_config(["weather", "city_code"]), text=final_text)
